import time

from selenium.webdriver import ActionChains

from libs.action import WebDriverAction
from libs.game import Game
from libs.image import ImageTool
from libs.log import Log
from libs.movement import Movement
from libs.task_helper import TaskHelper
from libs.trade_helper import TradeHelper
from libs.window import AdsWindow

if __name__ == "__main__":
    parser = TaskHelper.default_args_parser('Throw')
    args = parser.parse_args()
    task_helper = TaskHelper.from_args(args)

    user_id = args.user_id
    log = Log(user_id)

    try:
        driver = AdsWindow(user_id).open(False)
        game = Game(driver, user_id)
        action = WebDriverAction(driver, user_id=user_id)
        movement = Movement(driver)
        image_tool = ImageTool(driver)
        trade_helper = TradeHelper(driver, user_id)
        ac = ActionChains(driver)
        throw_items = [
            'Basic Axe',
            'Basic Shears',
            'Basic Soil',
            'Basic Metalworking Kit',
            'Basic Stoneshaping Kit',
            'Basic Mine Kit',
            'Clayum Brick',
            'Remover',
            'Mover',
            'Crafting Mix',
        ]

        sell_items = [
            'Stick',
            'Stool',
            'Log Decoration',
            'Silk Slug',
            'Improved Stove Kit',
            'Wax',
            'Honey'
        ]

        game.enter_game()

        dustbin_image = 'dustbin.png'
        for _ in range(3):
            action.goto_spec()
            action.goto_land(3450)
            movement.keep_move_up(1.5)
            movement.keep_move_right(3)
            action.move_to(dustbin_image, max_loop=3)

            time.sleep(1)
            dustbin_loc = image_tool.find_target(dustbin_image)
            if dustbin_loc:
                dustbin_x, dustbin_y = dustbin_loc
                throw_count = game.chest_in(dustbin_x, dustbin_y, throw_items)
                log.debug(f'throw_count={throw_count}')
                if throw_count <= 6:
                    break

        trade_helper.goto_sell_position()
        trade_helper.open_shop_sell()
        for sell_name in sell_items:
            trade_helper.sell_item(sell_name, sell_qty=1111, price_delta=-1)
        action.escape()
        action.escape()

        action.goto_spec()
        task_helper.task_success()
    except Exception as e:
        task_helper.task_fail()
        TaskHelper(user_id).add_task('throw.py', delay_seconds=0, ignore_running=True, priority=9, retry=True)
        raise e